package com.akk.platform.manage;

import com.akk.module.avs.entity.AvsApplyCard;
import com.akk.module.avs.entity.AvsApplyLoan;
import com.akk.module.avs.entity.AvsIncreRecord;
import com.akk.module.avs.model.response.AvsIncreRecordRes;
import com.akk.module.avs.service.AvsApplyCardService;
import com.akk.module.avs.service.AvsApplyLoanService;
import com.akk.module.avs.service.AvsIncreReocrdService;
import com.akk.utils.*;
import com.akk.utils.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/platform/manage/increRecord/")
public class IncreRecordAction {

    @Autowired
    private AvsIncreReocrdService increReocrdService;

    @Autowired
    private WriteExcel writeExcel;

    @Autowired
    private AvsApplyLoanService applyLoanService;

    @Autowired
    private AvsApplyCardService applyCardService;

    @RequestMapping(value = "/list")
    @RequiresPermissions("sys:increRecord:list")
    public RestResponse list(@Valid Query query, BindingResult bindingResult,HttpServletRequest request){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage(),null);
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<AvsIncreRecordRes> list = increReocrdService.queryByParamsAndTd(query.getSearch());
        return RestResponse.build(PageUtils.buildPage(list,(int) new PageInfo<>(list).getTotal(),query));
    }

    @RequestMapping(value = "/info/{id}")
    @RequiresPermissions("sys:increRecord:info")
    public RestResponse info(@PathVariable Long id){
        AvsIncreRecord increRecordEntity = increReocrdService.queryById(id);
        if (increRecordEntity == null)
            return RestResponse.build("1","信息不存在");
        return RestResponse.build(increRecordEntity);
    }

    @RequestMapping(value = "/download")
    public void download(Query query, HttpServletResponse response) {
        List<AvsIncreRecordRes> datas = null;
        String title = "";
        Map params = query.getSearch();
        if (params.containsKey("startDate") && params.containsKey("endDate")){
            title += params.get("startDate").toString() + " - " + params.get("endDate").toString();
        }
        if (params.containsKey("typeId")){
            if (params.containsKey("type")){
                if (params.get("type").toString().equals("loan")){
                    AvsApplyLoan loan = applyLoanService.queryById(Long.valueOf(params.get("typeId").toString()));
                    title += loan.getLoanName();
                } else{
                    AvsApplyCard card = applyCardService.queryById(Long.valueOf(params.get("typeId").toString()));
                    title += card.getCardBankName();
                }
            }
        }
        if (params.containsKey("type")){
            if (params.get("type").toString().equals("loan"))
                title += "贷款";
            else
                title += "信用卡";
        }
        title += "增值记录";
        datas = increReocrdService.queryByParamsAndTd(params);
        downloadExcelFile(title,datas,response);
    }

    @RequestMapping(value = "/cardList")
    public RestResponse cardList(){
        List<AvsApplyCard> list = applyCardService.queryAll();
        return RestResponse.build(list);
    }

    @RequestMapping(value = "/loanList")
    public RestResponse loanList(){
        List<AvsApplyLoan> list = applyLoanService.queryByParams(new HashMap());
        return RestResponse.build(list);
    }

    @RequestMapping(value = "/type/{type}/{id}")
    @RequiresPermissions("sys:increRecord:type")
    public RestResponse type(@PathVariable String type, @PathVariable Long id){
        if (type.equals("loan")){
            AvsApplyLoan loanEntity = applyLoanService.queryById(id);
            if (loanEntity == null)
                return RestResponse.build("1","信息不存在");
            else
                return RestResponse.build(loanEntity);
        }else if(type.equals("card")){
            AvsApplyCard cardEntity = applyCardService.queryById(id);
            if (cardEntity == null)
                return RestResponse.build("1","信息不存在");
            else
                return RestResponse.build(cardEntity);
        }
        return RestResponse.build("1","未知错误");
    }

    //Web 导出excel
    public void downloadExcelFile(String title, List<AvsIncreRecordRes> datas, HttpServletResponse response){
        try {
            String[] titles = {"编号","用户名","手机号","类型","通道ID","使用时间","产品名称"};
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            String jsonStr = gson.toJson(datas);
            Map<String,String> values = new HashMap();
            values.put("loan","贷款");
            values.put("card","信用卡");
            Map<String,Map<String,String>> replace = new HashMap<>();
            replace.put("type",values);
            Map<Integer,Integer> columnWidth = new HashMap<>();
            columnWidth.put(0,20);
            columnWidth.put(1,20);
            columnWidth.put(2,20);
            columnWidth.put(3,20);
            columnWidth.put(4,20);
            columnWidth.put(5,30);
            columnWidth.put(6,20);
            File file = writeExcel.exportExcel(title,jsonStr,titles,replace,columnWidth,null);
            InputStream is = new FileInputStream(file);
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((title + ".xls").getBytes(), "ISO-8859-1"));
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);
            byte[] buff = new byte[8192];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            is.close();
            bis.close();
            bos.close();
            outputStream.flush();
            outputStream.close();
            file.delete();
        }catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("导出Excel失败");
        }
    }

}
